

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
    <meta name="description" content="参考文档 : 点击查看@[TOC]  运行环境  Chrome JDK8  IDEA 2021.3 旗舰版 Visual Status Code 2022 带 Live Server插件（可快速解析Web的HTML、CSS、JavaScript）  一、OSS相关概念 官方文档：点击查看  OSS 全称 Object Storage Service，即对象存储服务，是由阿里云提供的海量、安全、低">
<meta property="og:type" content="article">
<meta property="og:title" content="阿里云OSS_对象存储服务快速入门_参考官方文档实现使用JavaSDK上传文件_本地上传与web上传案例">
<meta property="og:url" content="http://example.com/2022/02/21/%E9%98%BF%E9%87%8C%E4%BA%91OSS%20_%20%E5%AF%B9%E8%B1%A1%E5%AD%98%E5%82%A8%E6%9C%8D%E5%8A%A1%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8%20_%20%E5%8F%82%E8%80%83%E5%AE%98%E6%96%B9%E6%96%87%E6%A1%A3%E5%AE%9E%E7%8E%B0%E4%BD%BF%E7%94%A8JavaSDK%E4%B8%8A%E4%BC%A0%E6%96%87%E4%BB%B6%20_%20%E6%9C%AC%E5%9C%B0%E4%B8%8A%E4%BC%A0%E4%B8%8Eweb%E4%B8%8A%E4%BC%A0%E6%A1%88%E4%BE%8B/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="参考文档 : 点击查看@[TOC]  运行环境  Chrome JDK8  IDEA 2021.3 旗舰版 Visual Status Code 2022 带 Live Server插件（可快速解析Web的HTML、CSS、JavaScript）  一、OSS相关概念 官方文档：点击查看  OSS 全称 Object Storage Service，即对象存储服务，是由阿里云提供的海量、安全、低">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/7c11a57b4be7418fa129ffc16652ce95.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/035d13568ab842369841739fe331b0e7.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/c7cb68407e614e1dbb4670e526c2c933.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/bb5e47eb103f44cb87452fad7066f486.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/39bb250260d547f8865f96034075d357.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/cdd100377c524310a56f07ff6ebbd24d.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/0e2cba19909641a797853ce586595416.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/25fc077832c64b6e906c55dab592986e.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/982c64e357c845a7b0116084841335a5.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/5043ffc1ac7740a686339a43da55403e.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/d6272b9af1474512bb603b23abf44a1c.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/462d7875cf70477cbaf101859a5c04e4.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/a20c2808f6ec46dfba0af21efaf637ea.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/cdb84c6f0ab746cf85e213f21b62c982.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/33feaaed783a4013a531508f973c9221.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/bece1b9da5b9465e9f38f0d9a70577e3.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2b53cd19ae2d4d4d9b13f86eb73250c7.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/6bdc9f0bd0bf420fb22c6975554dbce5.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/ba087329adee4c29a8f4dd0810259d39.png">
<meta property="article:published_time" content="2022-02-21T14:20:51.000Z">
<meta property="article:modified_time" content="2022-08-22T15:41:33.666Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="阿里云OSS">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/7c11a57b4be7418fa129ffc16652ce95.png">
  
  
  
  <title>阿里云OSS_对象存储服务快速入门_参考官方文档实现使用JavaSDK上传文件_本地上传与web上传案例 - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>尤 Ni&#39;s Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="阿里云OSS_对象存储服务快速入门_参考官方文档实现使用JavaSDK上传文件_本地上传与web上传案例"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        John Doe
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-02-21 22:20" pubdate>
          2022年2月21日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          10k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          84 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">阿里云OSS_对象存储服务快速入门_参考官方文档实现使用JavaSDK上传文件_本地上传与web上传案例</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：1 小时前
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <blockquote>
<p>参考文档 : <a target="_blank" rel="noopener" href="https://www.cnblogs.com/l-y-h/p/12805028.html">点击查看</a><br>@[TOC]</p>
</blockquote>
<h1 id="运行环境"><a href="#运行环境" class="headerlink" title="运行环境"></a>运行环境</h1><hr>
<ul>
<li>Chrome</li>
<li>JDK8 </li>
<li>IDEA 2021.3 旗舰版</li>
<li>Visual Status Code 2022 带 Live Server插件（可快速解析Web的HTML、CSS、JavaScript）</li>
</ul>
<h1 id="一、OSS相关概念"><a href="#一、OSS相关概念" class="headerlink" title="一、OSS相关概念"></a>一、OSS相关概念</h1><hr>
<p>官方文档：<a target="_blank" rel="noopener" href="https://help.aliyun.com/document_detail/31817.html">点击查看</a></p>
<blockquote>
<p>OSS 全称 Object Storage Service，即对象存储服务，是由阿里云提供的海量、安全、低成本、高可靠的云存储服务。</p>
</blockquote>
<blockquote>
<p>OSS具有与平台无关的RESTful API接口，可在任意应用、任意地点存储与访问任何类型的数据。网站的图片、视频等文件就可以存放在OSS中（海量数据，交给阿里云平台维护，安全可靠）</p>
</blockquote>
<h2 id="1-1-Storage-Class-存储类型"><a href="#1-1-Storage-Class-存储类型" class="headerlink" title="1.1 Storage Class 存储类型"></a>1.1 Storage Class 存储类型</h2><p>有标准、低频访问、归档、冷归档四种存储类型，价格依次递减</p>
<ul>
<li><p>标准：高持久、高可哦那个、高性能，支持频繁的数据访问</p>
</li>
<li><p>低频访问：适合长期保存不经常访问的数据（平均每月1-2次频率）</p>
</li>
<li><p>归档：适合需长期保存（建议半年以上）的数据</p>
</li>
<li><p>冷归档：适合超长事件存放的极冷数据</p>
</li>
</ul>
<h2 id="1-2-Bucket-存储空间"><a href="#1-2-Bucket-存储空间" class="headerlink" title="1.2 Bucket 存储空间"></a>1.2 Bucket 存储空间</h2><p>存储空间是用于存储对象（Object）的容器。</p>
<p>具有各种配置属性，包括地域、访问权限、存储类型等。</p>
<h2 id="1-3-Object-对象"><a href="#1-3-Object-对象" class="headerlink" title="1.3 Object 对象"></a>1.3 Object 对象</h2><p>OSS存储数据的基本单元，同时被称作OSS的文件。</p>
<p>Object 由Object Meta、Data和Key组成，即元信息、用户数据和文件名。</p>
<p>Object 由 Bucket内部唯一的Key来表示</p>
<p>Object Meta 元信息是一组键值对，表示了Object的一些属性，比如最后修改时间、大小等信息，同时也可以自定义信息。</p>
<h2 id="1-4-Region-地域"><a href="#1-4-Region-地域" class="headerlink" title="1.4 Region 地域"></a>1.4 Region 地域</h2><p>OSS的数据中心所在物理位置，在创建Bucket时徐选择合适的地域。</p>
<h2 id="1-5-Endpoint-访问域名"><a href="#1-5-Endpoint-访问域名" class="headerlink" title="1.5 Endpoint 访问域名"></a>1.5 Endpoint 访问域名</h2><p>OSS对外服务的访问域名，通过域名存储、获取对象。</p>
<h2 id="1-6-AccessKet-访问密钥"><a href="#1-6-AccessKet-访问密钥" class="headerlink" title="1.6 AccessKet 访问密钥"></a>1.6 AccessKet 访问密钥</h2><p>AccessKey 简称AK，指访问身份验证中用到的AK ID 和 AK Secret，前者用于标识用户，后者表示该用户的密钥。</p>
<h1 id="二、使用阿里云OSS服务"><a href="#二、使用阿里云OSS服务" class="headerlink" title="二、使用阿里云OSS服务"></a>二、使用阿里云OSS服务</h1><hr>
<h2 id="2-1-开通OSS服务"><a href="#2-1-开通OSS服务" class="headerlink" title="2.1 开通OSS服务"></a>2.1 开通OSS服务</h2><p>访问阿里云官网：<a target="_blank" rel="noopener" href="https://oss.console.aliyun.com/">https://oss.console.aliyun.com/</a></p>
<p>注册账号（过程略）后搜索OSS对象存储服务，点击立即开通</p>
<p><img src="https://img-blog.csdnimg.cn/7c11a57b4be7418fa129ffc16652ce95.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h2 id="2-2-创建-Bucket（存储空间）"><a href="#2-2-创建-Bucket（存储空间）" class="headerlink" title="2.2 创建 Bucket（存储空间）"></a>2.2 创建 Bucket（存储空间）</h2><p>在OSS管理页面中创建存储空间（Bucket）</p>
<p><img src="https://img-blog.csdnimg.cn/035d13568ab842369841739fe331b0e7.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>按照自己的需求进行设置</p>
<p><img src="https://img-blog.csdnimg.cn/c7cb68407e614e1dbb4670e526c2c933.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h2 id="2-3-在网页上传文件"><a href="#2-3-在网页上传文件" class="headerlink" title="2.3 在网页上传文件"></a>2.3 在网页上传文件</h2><p>用途一：手动上传文件</p>
<p><img src="https://img-blog.csdnimg.cn/bb5e47eb103f44cb87452fad7066f486.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p><img src="https://img-blog.csdnimg.cn/39bb250260d547f8865f96034075d357.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>点击详情可直接下载文件或者复制文件的URL<br><img src="https://img-blog.csdnimg.cn/cdd100377c524310a56f07ff6ebbd24d.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h2 id="2-4-创建用户，生成AccesskeyID与Secret"><a href="#2-4-创建用户，生成AccesskeyID与Secret" class="headerlink" title="2.4 创建用户，生成AccesskeyID与Secret"></a>2.4 创建用户，生成AccesskeyID与Secret</h2><p>AccessKey就相当于一个账号和密码，可以视为小号，这里主要用于访问之前创建的存储空间。</p>
<p>将鼠标移至阿里云网站右上角的头像，选择访问控制， </p>
<p><img src="https://img-blog.csdnimg.cn/0e2cba19909641a797853ce586595416.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>第二步，点击创建用户</p>
<p><img src="https://img-blog.csdnimg.cn/25fc077832c64b6e906c55dab592986e.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>第三步，设置登录名称和显示名称后，选中Open API 调用访问选择框</p>
<p><img src="https://img-blog.csdnimg.cn/982c64e357c845a7b0116084841335a5.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>第四步，创建用户成功，自动生成了AccessKey对应的ID和Secret<br><img src="https://img-blog.csdnimg.cn/5043ffc1ac7740a686339a43da55403e.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h2 id="2-5-为用户添加读权限"><a href="#2-5-为用户添加读权限" class="headerlink" title="2.5 为用户添加读权限"></a>2.5 为用户添加读权限</h2><p>第一步，选中当前的用户，点击添加权限<br><img src="https://img-blog.csdnimg.cn/d6272b9af1474512bb603b23abf44a1c.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>第二步，根据需要添加权限，比如管理OSS权限还有只读OSS的权限</p>
<p><img src="https://img-blog.csdnimg.cn/462d7875cf70477cbaf101859a5c04e4.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h1 id="三、使用JavaSDK操作OSS"><a href="#三、使用JavaSDK操作OSS" class="headerlink" title="三、使用JavaSDK操作OSS"></a>三、使用JavaSDK操作OSS</h1><hr>
<h2 id="3-1-操作一：测试连接"><a href="#3-1-操作一：测试连接" class="headerlink" title="3.1 操作一：测试连接"></a>3.1 操作一：测试连接</h2><p>官方文档：<a target="_blank" rel="noopener" href="https://help.aliyun.com/document_detail/32008.html">点击查看</a></p>
<p>第一步，Maven引入依赖</p>
<p><code>pom.xml</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.aliyun.oss<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>aliyun-sdk-oss<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>3.13.2<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>第二步，编写Java代码，（其他地域的访问映射 <a target="_blank" rel="noopener" href="https://help.aliyun.com/document_detail/31837.htm">点击访问</a>）</p>
<p><img src="https://img-blog.csdnimg.cn/a20c2808f6ec46dfba0af21efaf637ea.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni;<br><br><span class="hljs-keyword">import</span> com.aliyun.oss.ClientException;<br><span class="hljs-keyword">import</span> com.aliyun.oss.OSS;<br><span class="hljs-keyword">import</span> com.aliyun.oss.OSSClientBuilder;<br><span class="hljs-keyword">import</span> com.aliyun.oss.OSSException;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">testOSS</span> &#123;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> Exception &#123;<br>        <span class="hljs-comment">// Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。关于其他Region对应的Endpoint信息，请参见访问域名和数据中心。</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">endpoint</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;https://oss-cn-hangzhou.aliyuncs.com&quot;</span>;<br>        <span class="hljs-comment">// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">accessKeyId</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;创建用户时生成的Bucket ID&quot;</span>;<br>        <span class="hljs-type">String</span> <span class="hljs-variable">accessKeySecret</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;创建用于时生成的Bucket Secret&quot;</span>;<br>        <span class="hljs-type">String</span> <span class="hljs-variable">bucketName</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;创建的用户&quot;</span>;<br><br>        <span class="hljs-comment">// 创建OSSClient实例。</span><br>        <span class="hljs-type">OSS</span> <span class="hljs-variable">ossClient</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">OSSClientBuilder</span>().build(endpoint, accessKeyId, accessKeySecret);<br><br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-comment">// 创建存储空间。</span><br>            ossClient.createBucket(bucketName);<br><br>        &#125; <span class="hljs-keyword">catch</span> (OSSException oe) &#123;<br>            System.out.println(<span class="hljs-string">&quot;Caught an OSSException, which means your request made it to OSS, &quot;</span><br>                    + <span class="hljs-string">&quot;but was rejected with an error response for some reason.&quot;</span>);<br>            System.out.println(<span class="hljs-string">&quot;Error Message:&quot;</span> + oe.getErrorMessage());<br>            System.out.println(<span class="hljs-string">&quot;Error Code:&quot;</span> + oe.getErrorCode());<br>            System.out.println(<span class="hljs-string">&quot;Request ID:&quot;</span> + oe.getRequestId());<br>            System.out.println(<span class="hljs-string">&quot;Host ID:&quot;</span> + oe.getHostId());<br>        &#125; <span class="hljs-keyword">catch</span> (ClientException ce) &#123;<br>            System.out.println(<span class="hljs-string">&quot;Caught an ClientException, which means the client encountered &quot;</span><br>                    + <span class="hljs-string">&quot;a serious internal problem while trying to communicate with OSS, &quot;</span><br>                    + <span class="hljs-string">&quot;such as not being able to access the network.&quot;</span>);<br>            System.out.println(<span class="hljs-string">&quot;Error Message:&quot;</span> + ce.getMessage());<br>        &#125; <span class="hljs-keyword">finally</span> &#123;<br>            <span class="hljs-keyword">if</span> (ossClient != <span class="hljs-literal">null</span>) &#123;<br>                ossClient.shutdown();<br>            &#125;<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>执行结果：</strong><br><img src="https://img-blog.csdnimg.cn/cdb84c6f0ab746cf85e213f21b62c982.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"><br>至此，OSS与Java连接成功。</p>
<h2 id="3-2-操作二：本地上传文件"><a href="#3-2-操作二：本地上传文件" class="headerlink" title="3.2 操作二：本地上传文件"></a>3.2 操作二：本地上传文件</h2><p>参考官方文档：<a target="_blank" rel="noopener" href="https://help.aliyun.com/document_detail/84781.htm">点击查看</a></p>
<p>第一步，导入Maven依赖（和之前一样）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java">&lt;dependency&gt;<br>    &lt;groupId&gt;com.aliyun.oss&lt;/groupId&gt;<br>    &lt;artifactId&gt;aliyun-sdk-oss&lt;/artifactId&gt;<br>    &lt;version&gt;<span class="hljs-number">3.13</span><span class="hljs-number">.2</span>&lt;/version&gt;<br>&lt;/dependency&gt;<br></code></pre></td></tr></table></figure>

<p>官方服务端下载地址：（用于参考）<a target="_blank" rel="noopener" href="https://gosspublic.alicdn.com/doc/91868/aliyun-oss-appserver-java-master.zip">点击下载</a><br><img src="https://img-blog.csdnimg.cn/33feaaed783a4013a531508f973c9221.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>第二步，参考官方提供的代码，编写JavaWeb上传文件的Java代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni;<br><br><span class="hljs-keyword">import</span> com.aliyun.oss.ClientException;<br><span class="hljs-keyword">import</span> com.aliyun.oss.OSS;<br><span class="hljs-keyword">import</span> com.aliyun.oss.OSSClientBuilder;<br><span class="hljs-keyword">import</span> com.aliyun.oss.OSSException;<br><span class="hljs-keyword">import</span> com.aliyun.oss.model.PutObjectRequest;<br><br><span class="hljs-keyword">import</span> java.io.File;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">testOSS</span> &#123;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> Exception &#123;<br>        <span class="hljs-comment">// Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">endpoint</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;https://oss-cn-hangzhou.aliyuncs.com&quot;</span>;<br>        <span class="hljs-comment">// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">accessKeyId</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;你的Bucket ID&quot;</span>;<br>        <span class="hljs-type">String</span> <span class="hljs-variable">accessKeySecret</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;你的 Bucket Secret&quot;</span>;<br>        <span class="hljs-comment">// 填写Bucket名称，例如examplebucket。</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">bucketName</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;unirithe&quot;</span>;<br>        <span class="hljs-comment">// 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">objectName</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;pom.xml&quot;</span>;<br>        <span class="hljs-comment">// 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。</span><br>        <span class="hljs-comment">// 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。</span><br>        String filePath= <span class="hljs-string">&quot;D:\\pom.xml&quot;</span>;<br><br>        <span class="hljs-comment">// 创建OSSClient实例。</span><br>        <span class="hljs-type">OSS</span> <span class="hljs-variable">ossClient</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">OSSClientBuilder</span>().build(endpoint, accessKeyId, accessKeySecret);<br><br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-comment">// 创建PutObjectRequest对象。</span><br>            <span class="hljs-type">PutObjectRequest</span> <span class="hljs-variable">putObjectRequest</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">PutObjectRequest</span>(bucketName, objectName, <span class="hljs-keyword">new</span> <span class="hljs-title class_">File</span>(filePath));<br>            <span class="hljs-comment">// 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。</span><br>            <span class="hljs-comment">// ObjectMetadata metadata = new ObjectMetadata();</span><br>            <span class="hljs-comment">// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());</span><br>            <span class="hljs-comment">// metadata.setObjectAcl(CannedAccessControlList.Private);</span><br>            <span class="hljs-comment">// putObjectRequest.setMetadata(metadata);</span><br><br>            <span class="hljs-comment">// 上传文件。</span><br>            ossClient.putObject(putObjectRequest);<br>        &#125; <span class="hljs-keyword">catch</span> (OSSException oe) &#123;<br>            System.out.println(<span class="hljs-string">&quot;Caught an OSSException, which means your request made it to OSS, &quot;</span><br>                    + <span class="hljs-string">&quot;but was rejected with an error response for some reason.&quot;</span>);<br>            System.out.println(<span class="hljs-string">&quot;Error Message:&quot;</span> + oe.getErrorMessage());<br>            System.out.println(<span class="hljs-string">&quot;Error Code:&quot;</span> + oe.getErrorCode());<br>            System.out.println(<span class="hljs-string">&quot;Request ID:&quot;</span> + oe.getRequestId());<br>            System.out.println(<span class="hljs-string">&quot;Host ID:&quot;</span> + oe.getHostId());<br>        &#125; <span class="hljs-keyword">catch</span> (ClientException ce) &#123;<br>            System.out.println(<span class="hljs-string">&quot;Caught an ClientException, which means the client encountered &quot;</span><br>                    + <span class="hljs-string">&quot;a serious internal problem while trying to communicate with OSS, &quot;</span><br>                    + <span class="hljs-string">&quot;such as not being able to access the network.&quot;</span>);<br>            System.out.println(<span class="hljs-string">&quot;Error Message:&quot;</span> + ce.getMessage());<br>        &#125; <span class="hljs-keyword">finally</span> &#123;<br>            <span class="hljs-keyword">if</span> (ossClient != <span class="hljs-literal">null</span>) &#123;<br>                ossClient.shutdown();<br>            &#125;<br>        &#125;<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>
<p><img src="https://img-blog.csdnimg.cn/bece1b9da5b9465e9f38f0d9a70577e3.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h2 id="3-3-操作三：在Web项目里实现OSS上传"><a href="#3-3-操作三：在Web项目里实现OSS上传" class="headerlink" title="3.3 操作三：在Web项目里实现OSS上传"></a>3.3 操作三：在Web项目里实现OSS上传</h2><p>本次案例采取直接在后端传输文件到OSS，还有一种方法是从后端发送签名到前端，由前端进行发送，后者效率更高，这里没有继续深入，暂时用后端实现简单的上传。</p>
<p>由于函数回调需要用到公网IP，这里就不测试了。</p>
<p>官方参考文档：<a target="_blank" rel="noopener" href="https://help.aliyun.com/document_detail/91868.html">点击查看</a></p>
<p>第一步，导入SDK Maven依赖（Web相关的依赖这里忽略了，请自行添加）<br><code>pom.xml</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.aliyun.oss<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>aliyun-sdk-oss<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>3.13.2<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>第二步，编写Controller层代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.controller;<br><br><span class="hljs-keyword">import</span> com.alibaba.fastjson.JSON;<br><span class="hljs-keyword">import</span> com.alibaba.fastjson.JSONObject;<br><span class="hljs-keyword">import</span> com.aliyun.oss.OSS;<br><span class="hljs-keyword">import</span> com.aliyun.oss.OSSClient;<br><span class="hljs-keyword">import</span> com.aliyun.oss.OSSClientBuilder;<br><span class="hljs-keyword">import</span> com.aliyun.oss.common.utils.BinaryUtil;<br><span class="hljs-keyword">import</span> com.aliyun.oss.model.MatchMode;<br><span class="hljs-keyword">import</span> com.aliyun.oss.model.PolicyConditions;<br><span class="hljs-keyword">import</span> org.springframework.stereotype.Controller;<br><span class="hljs-keyword">import</span> org.springframework.web.bind.annotation.GetMapping;<br><span class="hljs-keyword">import</span> org.springframework.web.bind.annotation.PostMapping;<br><span class="hljs-keyword">import</span> org.springframework.web.bind.annotation.RestController;<br><br><span class="hljs-keyword">import</span> javax.servlet.http.HttpServletResponse;<br><span class="hljs-keyword">import</span> java.nio.charset.StandardCharsets;<br><span class="hljs-keyword">import</span> java.time.LocalDateTime;<br><span class="hljs-keyword">import</span> java.time.format.DateTimeFormatter;<br><span class="hljs-keyword">import</span> java.util.*;<br><br><span class="hljs-meta">@RestController</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">OssController</span> &#123;<br>    <span class="hljs-meta">@GetMapping(&quot;/oss/test&quot;)</span><br>    <span class="hljs-keyword">public</span> String <span class="hljs-title function_">testOss</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-type">String</span> <span class="hljs-variable">accessId</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;待填写&quot;</span>; <span class="hljs-comment">// 请填写您的AccessKeyId。</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">accessKey</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;待填写&quot;</span>; <span class="hljs-comment">// 请填写您的AccessKeySecret。</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">endpoint</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;待填写&quot;</span>; <span class="hljs-comment">// 请填写您的 endpoint，比如杭州oss-cn-hangzhou.aliyuncs.com。</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">bucket</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;待填写&quot;</span>; <span class="hljs-comment">// 请填写您的 bucketname 。</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">host</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;https://&quot;</span> + bucket + <span class="hljs-string">&quot;.&quot;</span> + endpoint; <span class="hljs-comment">// host的格式为 bucketname.endpoint</span><br>        <span class="hljs-comment">// jasonCallback 上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实信息。</span><br><span class="hljs-comment">//        String callbackUrl = &quot;http://localhost:8080/oss/test&quot;;</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">dir</span> <span class="hljs-operator">=</span> DateTimeFormatter.ofPattern(<span class="hljs-string">&quot;yyyy-MM-dd-&quot;</span>).format(LocalDateTime.now()) + <span class="hljs-string">&quot;/&quot;</span>; <span class="hljs-comment">// 用户上传文件时指定的前缀。</span><br><br>        Map&lt;String, String&gt; respMap = <span class="hljs-keyword">new</span> <span class="hljs-title class_">LinkedHashMap</span>&lt;String, String&gt;();<br>        <span class="hljs-type">JSONObject</span> <span class="hljs-variable">jasonCallback</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">JSONObject</span>();<br><br>        <span class="hljs-comment">// 创建OSSClient实例</span><br>        <span class="hljs-type">OSS</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">OSSClientBuilder</span>().build(endpoint, accessId, accessKey);<br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-type">long</span> <span class="hljs-variable">expireTime</span> <span class="hljs-operator">=</span> <span class="hljs-number">30</span>;<br>            <span class="hljs-type">long</span> <span class="hljs-variable">expireEndTime</span> <span class="hljs-operator">=</span> System.currentTimeMillis() + expireTime * <span class="hljs-number">1000</span>;<br>            <span class="hljs-type">Date</span> <span class="hljs-variable">expiration</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>(expireEndTime);<br>            <span class="hljs-type">PolicyConditions</span> <span class="hljs-variable">policyConds</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">PolicyConditions</span>();<br>            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, <span class="hljs-number">0</span>, <span class="hljs-number">1048576000</span>);<br>            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);<br><br>            <span class="hljs-type">String</span> <span class="hljs-variable">postPolicy</span> <span class="hljs-operator">=</span> client.generatePostPolicy(expiration, policyConds);<br>            <span class="hljs-type">byte</span>[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);<br>            <span class="hljs-type">String</span> <span class="hljs-variable">encodedPolicy</span> <span class="hljs-operator">=</span> BinaryUtil.toBase64String(binaryData);<br>            <span class="hljs-type">String</span> <span class="hljs-variable">postSignature</span> <span class="hljs-operator">=</span> client.calculatePostSignature(postPolicy);<br><br>            System.out.println(<span class="hljs-string">&quot;policy:&quot;</span> + Arrays.toString(binaryData));<br>            respMap.put(<span class="hljs-string">&quot;accessid&quot;</span>, accessId);<br>            respMap.put(<span class="hljs-string">&quot;policy&quot;</span>, encodedPolicy);<br>            respMap.put(<span class="hljs-string">&quot;signature&quot;</span>, postSignature);<br>            respMap.put(<span class="hljs-string">&quot;dir&quot;</span>, dir);<br>            respMap.put(<span class="hljs-string">&quot;host&quot;</span>, host);<br>            respMap.put(<span class="hljs-string">&quot;expire&quot;</span>, String.valueOf(expireEndTime / <span class="hljs-number">1000</span>));<br><br><span class="hljs-comment">//            jasonCallback.put(&quot;callbackUrl&quot;, callbackUrl);</span><br><span class="hljs-comment">//            jasonCallback.put(&quot;callbackBody&quot;,</span><br><span class="hljs-comment">//                    &quot;filename=$&#123;object&#125;&amp;size=$&#123;size&#125;&amp;mimeType=$&#123;mimeType&#125;&amp;height=$&#123;imageInfo.height&#125;&amp;width=$&#123;imageInfo.width&#125;&quot;);</span><br><span class="hljs-comment">//            jasonCallback.put(&quot;callbackBodyType&quot;, &quot;application/x-www-form-urlencoded&quot;);</span><br><span class="hljs-comment">//            String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());</span><br><span class="hljs-comment">//            respMap.put(&quot;callback&quot;, base64CallbackBody);</span><br><span class="hljs-comment">//            response.setHeader(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;);</span><br><span class="hljs-comment">//            response.setHeader(&quot;Access-Control-Allow-Methods&quot;, &quot;POST&quot;);</span><br>        &#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;<br>            System.out.println(e.getMessage());<br>        &#125;<br>        <span class="hljs-keyword">return</span> JSON.toJSONString(<span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;String, Object&gt;()&#123;&#123;<br>            put(<span class="hljs-string">&quot;Code&quot;</span>, <span class="hljs-number">1</span>);<br>            put(<span class="hljs-string">&quot;Status&quot;</span>, <span class="hljs-string">&quot;success&quot;</span>);<br>            put(<span class="hljs-string">&quot;items&quot;</span> ,respMap);<br><span class="hljs-comment">//            put(&quot;jasonCallback&quot;, jasonCallback);</span><br>        &#125;&#125;);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>


<p>第三步，下载客户端进行回调测试</p>
<p>官方下载地址：<a target="_blank" rel="noopener" href="https://docs-aliyun.cn-hangzhou.oss.aliyun-inc.com/assets/attach/86983/APP_zh/1537971352825/aliyun-oss-appserver-js-master.zip?file=aliyun-oss-appserver-js-master.zip">点击下载</a><br><img src="https://img-blog.csdnimg.cn/2b53cd19ae2d4d4d9b13f86eb73250c7.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>选择本地文件，点击开始上传，出现跨域错误<br><img src="https://img-blog.csdnimg.cn/6bdc9f0bd0bf420fb22c6975554dbce5.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h3 id="设置CORS解决跨域问题"><a href="#设置CORS解决跨域问题" class="headerlink" title="设置CORS解决跨域问题"></a>设置CORS解决跨域问题</h3><p>OSS 修改 CORS，解决跨域问题<br>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/38cb03ccf1e2455eaa223bca9f5e15eb.png#">https://img-blog.csdnimg.cn/38cb03ccf1e2455eaa223bca9f5e15eb.png#</a> &#x3D;50%x)<br>根据自身需要设置跨域规则<br>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/a2059417f42b4e7e86d927b67b9a1234.png#">https://img-blog.csdnimg.cn/a2059417f42b4e7e86d927b67b9a1234.png#</a> &#x3D;50%x)</p>
<p>再次访问前端项目，上传成功！<br><img src="https://img-blog.csdnimg.cn/ba087329adee4c29a8f4dd0810259d39.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E4%BA%91%E6%9C%8D%E5%8A%A1/" class="category-chain-item">云服务</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/%E9%98%BF%E9%87%8C%E4%BA%91OSS/">#阿里云OSS</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>阿里云OSS_对象存储服务快速入门_参考官方文档实现使用JavaSDK上传文件_本地上传与web上传案例</div>
      <div>http://example.com/2022/02/21/阿里云OSS _ 对象存储服务快速入门 _ 参考官方文档实现使用JavaSDK上传文件 _ 本地上传与web上传案例/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>John Doe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年2月21日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/02/22/Web%E9%A1%B9%E7%9B%AE%E5%AE%9E%E6%88%98%20_%20%E8%B4%AD%E7%89%A9%E7%B3%BB%E7%BB%9Fv2.0%20_%20%E5%BC%80%E5%8F%91%E8%AE%B0%E5%BD%95%EF%BC%88%E5%8D%81%EF%BC%89SpringBoot%E6%95%B4%E5%90%88%E9%98%BF%E9%87%8C%E4%BA%91OSS%E5%AF%B9%E8%B1%A1%E5%AD%98%E5%82%A8%E6%9C%8D%E5%8A%A1%20_%20Web%E5%B0%86%E4%B8%8A%E4%BC%A0%E7%9A%84%E5%95%86%E5%93%81%E5%9B%BE%E7%89%87%E4%BF%9D%E5%AD%98%E5%88%B0%E9%98%BF%E9%87%8C%E4%BA%91%EF%BC%8C%E5%90%8C%E6%97%B6%E5%B0%86%E5%9C%B0%E5%9D%80%E4%BF%9D%E5%AD%98%E5%88%B0%E6%95%B0%E6%8D%AE%E5%BA%93/" title="Web项目实战 _ 购物系统v2.0 _ 开发记录（十）SpringBoot整合阿里云OSS对象存储服务 _ Web将上传的商品图片保存到阿里云，同时将地址保存到数据库">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Web项目实战 _ 购物系统v2.0 _ 开发记录（十）SpringBoot整合阿里云OSS对象存储服务 _ Web将上传的商品图片保存到阿里云，同时将地址保存到数据库</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/02/17/2022%E5%B9%B4%E6%9C%80%E6%96%B0%20%E9%AB%98%E6%B8%85%E5%AD%A6%E4%B9%A0%E8%B7%AF%E7%BA%BF%E5%9B%BE%20_%20Java%E3%80%81%E5%A4%A7%E6%95%B0%E6%8D%AE%E3%80%81UI_UE/" title="2022年最新 高清学习路线图 _ Java、大数据、UI_UE">
                        <span class="hidden-mobile">2022年最新 高清学习路线图 _ Java、大数据、UI_UE</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
